package com.df.excel_export.listener;

import com.df.excel_export.utils.SpringContextUtil;
import com.df.excel_export.validator.IFieldValidator;
import com.df.excel_export.validator.IValidatorFactory;
import com.df.excel_export.validator.ValidatorManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
public class AppReadyListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    List<IValidatorFactory> factories;

    @Autowired
    ServletWebServerApplicationContext context;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        SpringContextUtil.getInstance().init(event.getApplicationContext());
        //TODO 加载脚本校验器
        if(factories!=null && !factories.isEmpty()) {
            ValidatorManager.registerValidatorFactory(factories);
        }

        //T自动打开浏览器访问
        CompletableFuture.runAsync( () -> {
            try {
                int port = context.getWebServer().getPort();
                Runtime.getRuntime().exec("cmd /c start "+"http://localhost:"+port);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
